var sha1 = require('sha1');
var express = require('express');
var router = express.Router();
var resultJson = require('../result-json');

var UserModel = require('../models/User');
var checkNotLogin = require('../middlewares/check').checkNotLogin;



// POST /login 用户登录
router.post('/login.json', checkNotLogin, function(req, res, next) {
    var name = req.body.name;
    var password = req.body.password;
    // console.log(req.body);
    // console.log('+++++++++++');
    if (!name){
        return res.send(resultJson(100));
    }
    UserModel.getUserByName(name)
        .then(function (user) {
            if (!user) {
                return res.send(resultJson(100));
            }
            // 检查密码是否匹配
            if (sha1(password) !== user.password) {
                return res.send(resultJson(101));
            }
            // 用户信息写入 session
            delete user.password;
            req.session.user = user;

            return res.send(resultJson(0, user));
        })
});

router.post('/signup.json', function(req, res, next){
    var ops = req.body;
    console.log(ops);


    // 待写入数据库的用户信息
    var user = {
        name: ops.name || '',
        password: sha1(ops.password || ''),
        gender: ops.gender || '',
        bio: ops.bio || '',
        avatar: ops.avatar || ''
    };
    // 用户信息写入数据库
    UserModel.create(user)
        .then(function (result) {
            // 此 user 是插入 mongodb 后的值，包含 _id
            user = result.ops[0];
            // 将用户信息存入 session
            delete user.password;
            req.session.user = user;
            
            res.send(resultJson(0, user));
        })
        .catch(function (e) {
            // 用户名被占用
            if (e.message.match('E11000 duplicate key')) {
                res.send(resultJson(102));
            }
            next(e);
        });
});

router.post('/loginOut.json', function(req, res, next){
    req.session.user = null;
    res.send(resultJson(0));
});



module.exports = router;